Constructors in C++

Posted on December 15, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

Constructors in C++ are special member functions within a class that are automatically invoked when an object of that class is created. Constructors initialize the object's data members, set up the object's state, and perform any necessary setup tasks. They have the same name as the class and do not have a return type.

Types of Constructors in C++:

Default Constructor:

A constructor with no parameters is called a default constructor. It is automatically invoked when an object is created without specifying any values

class MyClass {
public:
// Default Constructor
MyClass() {
// Initialization code goes here
}
};

Parameterized Constructor:

A constructor with parameters is called a parameterized constructor. It allows you to initialize the object with specific values at the time of creation.

class Car {
private:
string brand;
int year;

public:
// Parameterized Constructor
Car(string brand, int year) {
this->brand = brand;
thisyear = year;
}
};

Copy Constructor:

A copy constructor creates a new object as a copy of an existing object. It is called when an object is passed by value or when an object is explicitly created as a copy of another object.

class Person {
private:
string name;
int age;

public:
// Copy Constructor
Person(const Person &other) {
this->name = other.name;
thisage = other.age;
}
};

Initializer List:

In C++, constructors can use an initializer list to initialize data members, providing a more efficient way to initialize member variables.

class Rectangle {
private:
int length;
int width;

public:
// Parameterized Constructor with Initializer List
Rectangle(int len, int wid) : length(len), width(wid) {
// No need for assignment in the constructor body
}
};

Understanding constructors is crucial for effective object initialization and proper resource management in C++ programs. Constructors help ensure that objects are in a valid and consistent state when they are created.